<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        :closable="false"
        show-icon
        center
        title="添加商品信息"
        type="info"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        center
        :space="200"
        align-center
        :active="activeName - 0"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addFrom" :rules="addFromRules" ref="fromAddRef">
        <el-tabs
          :before-leave="tabsBeforeLeave"
          tab-position="left"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addFrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addFrom.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addFrom.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addFrom.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
                v-model="addFrom.goods_cat"
                :options="goodsCate"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- checkList -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(item, i) in item.attr_vals"
                  :key="i"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://liufusong.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="header"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addFrom.goods_introduce"></quill-editor>
            <el-button @click="addGoods" type="primary" style="margin: 10px 0"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 展示图片对话框 -->
    <el-dialog title="提示" :visible.sync="previewDialogVisible" width="50%">
      <img style="width: 100%" :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeName: '',
      // 添加表单数据
      addFrom: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: ''
      },
      // 添加表单校验规则
      addFromRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 获取商品分类数据
      goodsCate: [],
      // 商品参数
      manyData: [],
      // 商品属性
      onlyData: [],
      // 文件上传请求头
      header: {
        Authorization: sessionStorage.getItem('token')
      },
      previewDialogVisible: false,
      // 预览的图片地址
      imgUrl: ''
    }
  },

  created() {
    this.getCateList()
  },

  methods: {
    async handleClick() {
      // console.log(this.activeName)
      // console.log(val)
      if (this.activeName === '1') {
        const res = await this.$axios.get(
          `categories/${this.addFrom.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyData = res.data

        // console.log(res)
        // console.log(this.mal888inyData)
      } else if (this.activeName === '2') {
        const res = await this.$axios.get(
          `categories/${this.addFrom.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyData = res.data
        console.log(res)
      }
    },
    // 获取商品分类数据
    async getCateList() {
      const res = await this.$axios.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.goodsCate = res.data
    },
    handleChange() {
      if (this.addFrom.goods_cat.length !== 3) {
        this.addFrom.goods_cat = []
      }
      console.log(this.addFrom.goods_cat)
    },
    // 阻止离开信息
    tabsBeforeLeave(newName, oldName) {
      if (oldName === '0' && this.addFrom.goods_cat.length !== 3) {
        this.$message.error('请选择必要的商品分类')
        return false
      }
    },
    handlePreview(file) {
      this.imgUrl = 'http://liufusong.top:8888/' + file.response.data.tmp_path
      console.log('http://liufusong.top:8888/' + file.response.data.tmp_path)
      this.previewDialogVisible = true
    },
    // 点击移除图片
    handleRemove(file) {
      const index = this.addFrom.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      console.log(index)
      this.addFrom.pics.splice(index, 1)
      console.log(this.addFrom)
    },
    // 图片上传成功
    handleSuccess(res) {
      // console.log(res)
      this.addFrom.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 点击添加商品
    addGoods() {
      this.$refs.fromAddRef.validate(async flag => {
        if (!flag) return this.$message.error('请填写必填项')
        console.log('发送请求')
        const form = _.cloneDeep(this.addFrom)
        form.goods_cat = form.goods_cat.join(',')
        form.attrs = []
        this.manyData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })

        this.onlyData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        const res = await this.$axios.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
        // 深拷贝后的数据是交给后台
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-steps {
  margin: 15px 0;
  /deep/.el-step__title {
    font-size: 13px;
  }
}
.el-checkbox {
  margin: 0;
}
.quill-editor {
  /deep/.ql-editor {
    height: 300px;
  }
}
</style>
